<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form ref="form" :inline="true" :model="queryData">
				<el-form-item :label="`${$t('common.choose_merchant')}:`">
					<merchant-select
						v-model="queryData.merchantId"
						v-symbols
					></merchant-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('system.system_configuration.formwork')}:`"
					prop="module"
				>
					<el-select
						v-model="queryData.module"
						size="medium"
						:placeholder="$t('common.select_all')"
						clearable
					>
						<el-option
							v-for="item in tabsArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						size="medium"
						:disabled="loading"
						:loading="loading"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-tabs v-model="queryData.type" @tab-click="handleClick">
				<el-tab-pane
					:label="`${$t('system.system_configuration.basic_config')}`"
					name="1"
				></el-tab-pane>
				<el-tab-pane
					:label="
						`${$t('system.system_configuration.member_config')}`
					"
					name="2"
				></el-tab-pane>
				<el-tab-pane
					:label="`${$t('system.system_configuration.agent_config')}`"
					name="3"
				></el-tab-pane>
				<el-tab-pane
					:label="`${$t('system.system_configuration.fund_config')}`"
					name="4"
				></el-tab-pane>
			</el-tabs>
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:data="dataList"
				:header-cell-style="getRowClass"
				highlight-current-row
				:max-height="tableHeight"
			>
				<el-table-column
					type="index"
					align="center"
					:label="$t('common.serial_number')"
					:width="getWidth('60px')"
				>
					<template slot-scope="scope">
						<span>{{ getSerialNum(scope.$index) }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="module"
					align="center"
					:label="$t('system.system_configuration.formwork')"
				>
					<template slot-scope="scope">
						{{ handleModule(scope.row.module) }}
					</template>
				</el-table-column>
				<el-table-column
					prop="configDes"
					align="center"
					:label="
						`${$t(
							'system.system_configuration.config_description'
						)}`
					"
					show-overflow-tooltip
				></el-table-column>
				<el-table-column
					prop="value"
					align="center"
					:label="$t('system.parameter_dictionary.value')"
				></el-table-column>
				<el-table-column
					prop="updatedBy"
					align="center"
					:label="$t('common.last_updateBy')"
				></el-table-column>
				<el-table-column
					prop="updatedAt"
					align="center"
					:label="$t('common.last_updateAt')"
				></el-table-column>
				<el-table-column
					prop="loginStatus"
					align="center"
					:label="$t('common.actions')"
				>
					<template slot-scope="scope">
						<el-button
							v-if="hasPermission('906011')"
							type="primary"
							@click="handleEdit(scope.row)"
						>
							{{ $t('system.versionnumberlist.edit') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				v-show="!!total"
				:current-page.sync="pageNum"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<el-dialog
			:title="$t('common.edit')"
			:visible.sync="dialogFormVisible"
			:destroy-on-close="true"
			:close-on-click-modal="false"
			:width="getWidth('580px', 1.6)"
		>
			<el-form ref="formSub" :model="dialogForm" :rules="rules">
				<el-form-item
					:label="`${$t('system.system_configuration.formwork')}:`"
					prop="module"
					class="elSelectContent"
				>
					<el-select
						v-model="dialogForm.module"
						size="medium"
						disabled
						style="width: 100%;"
					>
						<el-option
							v-for="item in tabsArr"
							:key="item.code"
							:label="item.description"
							:value="item.code * 1"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					:label="
						`${$t(
							'system.system_configuration.config_description'
						)}:`
					"
					prop="configDes"
				>
					<el-input
						v-model.trim="dialogForm.configDes"
						type="textarea"
						rows="3"
						disabled
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('system.parameter_dictionary.value')}:`"
					prop="value"
				>
					<el-input
						v-model.trim="dialogForm.value"
						autocomplete="off"
						clearable
						v-input="{ name: 'noEmpty' }"
						@input="
							onModuleValueInput(
								dialogForm.module,
								dialogForm.personId
							)
						"
					>
						<!-- <template
							v-if="amountModules.includes(dialogForm.module)"
							slot="prepend"
						>
							{{ handleCurrency(dialogForm.currency, true) }}
						</template> -->
					</el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button
					type="primary"
					:disabled="dialogFormLoading"
					:loading="dialogFormLoading"
					@click="submitEdit"
				>
					{{ $t('common.submit') }}
				</el-button>
			</div>
		</el-dialog>
		<GoogleKeyInput
			:isShowdialog="isShowdialog"
			@getGoogleKey="getGoogleKey($event)"
			@backPrevStep="backPrevStep()"
		></GoogleKeyInput>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import { mapGetters } from 'vuex'
import { POS_INT_PATTERN } from '@/utils/pattern'
import MainContent from '@/components/MainContent/index.vue'
export default {
	// eslint-disable-next-line vue/name-property-casing
	name: 'systemConfiguration',
	components: {
		GoogleKeyInput: () => import('@/components/GoogleKeyInput'),
		MainContent
	},
	mixins: [list],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: ['innerTabS'],
			queryData: {
				merchantId: undefined,
				module: undefined,
				type: '1'
			},
			dataList: [],
			tabsArr: [],
			isShowdialog: false,
			menuTypeArr: [],
			dialogFormVisible: false,
			dialogFormLoading: false,
			dialogForm: {},
			valuePersonId: 0, // 值类型
			amountModules: [6, 7, 8, 9, 10, 13, 14, 21, 23, 24] // 金额的模块可以字符串
		}
	},
	computed: {
		...mapGetters(['merchantInfo']),
		rules() {
			const testValue = (rule, value, callback) => {
				if (!value) {
					return callback(new Error('请输入'))
				}
				// 11代理配置-活跃会员
				// 12代理配置-有效活跃会员
				if (this.valuePersonId === 11 || this.valuePersonId === 12) {
					const message =
						'有效值为数字，逗号隔开，只能输入两个，比如：100,200'
					const valueArr = this.dialogForm.value.split(',')
					if (valueArr.length !== 2) {
						return callback(new Error(message))
					}
					if (
						!POS_INT_PATTERN.test(valueArr[0]) ||
						!POS_INT_PATTERN.test(valueArr[1])
					) {
						return callback(new Error(message))
					}
				}
				return callback()
			}
			return {
				value: [
					{
						required: true,
						trigger: 'blur',
						validator: testValue
					}
				]
			}
		}
		// tabsArr() {
		// 	let arr = []
		// 	switch (this.queryData.type) {
		// 		case '1':
		// 			arr = this.globalDics.personConfigFoundModule || []
		// 			break
		// 		case '2':
		// 			arr = this.globalDics.personConfigMemberModule || []
		// 			break
		// 		case '3':
		// 			arr = this.globalDics.personConfigProxyModule || []
		// 			break
		// 		case '4':
		// 			arr = this.globalDics.personConfigModule || []
		// 			break
		// 	}
		// 	return arr
		// }
	},
	watch: {
		'merchantInfo.id': {
			handler(newVal) {
				if (newVal) {
					this.queryData.merchantId = newVal
				} else {
					this.queryData.merchantId = undefined
				}
			},
			immediate: true
		},
		'queryData.merchantId': {
			handler(newVal) {
				this.queryData.module = undefined
				this.queryData.type = '1'
				if (newVal) {
					this.pageNum = 1
					this.loadData()
				}
			}
		}
	},
	created() {
		this.loadListModules()
	},
	methods: {
		onModuleValueInput(modual, personId) {
			//  非金额模块只能输入数字
			if (!this.amountModules.includes(modual)) {
				this.dialogForm.value = this.dialogForm.value.replace(
					/[^\d]+/g,
					''
				)
			}
			if (personId === 11 || personId === 12) {
				// 11代理配置-活跃会员
				// 12代理配置-有效活跃会员
				this.dialogForm.value = this.dialogForm.value.replace('，', ',')
			}
		},
		// 输入值校验
		onModuleValueInputBak(modual, personId) {
			//  非金额模块只能输入数字
			if (!this.amountModules.includes(modual)) {
				this.dialogForm.value = this.dialogForm.value.replace(
					/[^\d]+/g,
					''
				)
			}
			const val = Number(this.dialogForm.value)
			if (
				personId === 6 ||
				personId === 14 ||
				personId === 15 ||
				personId === 16
			) {
				// 会员配置-登录
				// 基础配置-验证码
				if (val > 50 || val < 1) {
					this.$message.warning('有效范围1-50整数')
					this.dialogForm.value = 1
				}
			} else if (personId === 13) {
				// 基础配置-手机号-验证码
				if (val > 100 || val < 1) {
					this.$message.warning('有效范围1-100整数')
					this.dialogForm.value = 1
				}
			} else if (personId === 7) {
				// 会员配置-消息中心
				if (val > 365 || val < 1) {
					this.$message.warning('有效范围1-365整数')
					this.dialogForm.value = 1
				}
			} else if (personId === 11 || personId === 12 || personId === 38) {
				// 11代理配置-活跃会员
				// 12代理配置-有效活跃会员
				// 38基础配置-活动
				this.dialogForm.value = this.dialogForm.value.replace(
					/[^\d]+/g,
					''
				)
				if (Number(this.dialogForm.value) < 1) {
					this.$message.warning('有效范围>1整数')
					this.dialogForm.value = 1
				}
			} else if (personId === 1) {
				const valueArr = ['0', '1']
				if (valueArr.indexOf(this.dialogForm.value.toString()) === -1) {
					this.dialogForm.value = 1
				}
			}
		},
		loadData() {
			const params = {
				...this.queryData,
				...this.getParams()
			}
			this.dataList = []
			// if (!this.queryData.merchantId) {
			// 	return
			// }
			this.loading = true
			this.$api
				.getPersonList(params)
				.then((res) => {
					this.loading = false
					const { record, totalRecord } = res.data || {}
					this.dataList = record || []
					this.total = totalRecord || 0
				})
				.catch(() => {
					this.loading = false
				})
		},
		loadListModules() {
			// 获取搜索框type下module
			let dicsArr = []
			switch (this.queryData.type) {
				case '1':
					dicsArr = this.globalDics.personConfigFoundModule || []
					break
				case '2':
					dicsArr = this.globalDics.personConfigMemberModule || []
					break
				case '3':
					dicsArr = this.globalDics.personConfigProxyModule || []
					break
				case '4':
					dicsArr = this.globalDics.personConfigModule || []
					break
			}
			this.tabsArr = dicsArr
			this.$api
				.getPersonListModules({ type: this.queryData.type })
				.then((res) => {
					if (Array.isArray(res?.data) && res?.data?.length > 0) {
						this.tabsArr = dicsArr.filter((item) => {
							return res.data.indexOf(Number(item.code)) > -1
						})
					}
				})
				.catch(() => {})
		},
		handleClick(val) {
			this.pageNum = 1
			this.queryData.module = undefined
			this.loadData()
			this.loadListModules()
		},
		handleEdit(val) {
			this.valuePersonId = val.personId
			this.dialogForm = { ...val }
			this.dialogFormVisible = true
		},
		submitEdit() {
			this.$refs.formSub.validate((valid) => {
				if (valid) {
					this.isShowdialog = true
				}
			})
		},
		backPrevStep() {
			this.dialogFormLoading = false
			this.isShowdialog = false
		},
		getGoogleKey(data) {
			this.dialogForm.googleVerifyCode = data
			this.isShowdialog = false
			this.dialogFormLoading = true
			this.$api
				.setPersonUpdatet(this.dialogForm)
				.then(() => {
					// setTimeout(() => {
					// 	this.dialogFormLoading = false
					// }, 500)
					this.$message.success(this.$t('common.modify_success'))
					this.dialogFormVisible = false
					this.dialogFormLoading = false
					this.loadData()
				})
				.catch(() => {
					this.dialogFormLoading = false
				})
		},
		handleModule(val) {
			return (
				this.tabsArr.find((item) => Number(item.code) === Number(val))
					?.description || '-'
			)
			// let text = '-'
			// switch (this.queryData.type) {
			// 	case '1':
			// 		text =
			// 			this.typeFilter(val, 'personConfigFoundModule') || '-'
			// 		break
			// 	case '2':
			// 		text =
			// 			this.typeFilter(val, 'personConfigMemberModule') || '-'
			// 		break
			// 	case '3':
			// 		text =
			// 			this.typeFilter(val, 'personConfigProxyModule') || '-'
			// 		break
			// 	case '4':
			// 		text = this.typeFilter(val, 'personConfigModule') || '-'
			// 		break
			// }
			// return text
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
}

::v-deep .elSelectContent .el-icon-arrow-up::before {
	content: '';
}
</style>
